package timo.rabbitmq.example.consumer.controller;

import cn.hutool.json.JSONObject;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import timo.rabbitmq.example.consumer.service.OrderService;

import java.util.List;
import java.util.Map;


@Component
@RabbitListener(queues="hello")
public class OrderConsumer {

    //收到订单数据后,会调用订单的业务代码,把订单保存到数据库
    @Autowired
    private OrderService orderService;

    @RabbitHandler  // 消息接收处理
    public void showMSG(String s,Channel channel, Message message){
        // 得到我们producer中发送的Object数据，此处可根据传过来的类型来选择接收，否则抛出异常
        System.out.println("收到的消息内容为：" + s);
        try {
//            orderService.saveOrder(object);
            //手动确认
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 可以进行重载，会找到指定参数的queue上
     * @param map
     */
    @RabbitHandler
    public void getMSG(Map map){
        System.out.println("wk2收到的（map）消息如下：" + map);
    }
    @RabbitHandler
    public void getMSG(List list){
        System.out.println("wk2收到的（list）消息如下：" + list);
    }
    //添加该注解后,会从指定的orderQueue接收消息,
    //并把数据转为 PdOrder 实例传递到此方法
//    @RabbitListener(queues="orderQueue")
    public void save(JSONObject object, Channel channel, Message message)
    {
        System.out.println("消费者");
        System.out.println(object.toString());
        try {
            orderService.saveOrder(object);
            //手动确认
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
